<template>
  <div class="expanded">
    <div class="main">
      <div class="contact" :class="{hidden:!showContact}">
        <Contact @handleSelectContactOffLine="handleSelectContactOffLine" :style="{width:showContact || !leftUser?'200px':'0px'}" @handleSelectContact="handleSelectContact" ref="contactBox" />
        <div v-if="!showContact && leftUser" class="toggle-contact" @click="toggleContact">
          <i class="el-icon-arrow-right" />
        </div>
        <div class="mask" @click="toggleContact"></div>
      </div>
      <div class="message">
        <div class="toolbar" v-if="leftUser">
          <div class="call-handle" v-if="leftUser.callOffer">
            <el-button type="text" size="small" style="color: #0091ff;" class="accept" @click="acceptCall">接受</el-button>
            <el-button type="text" size="small" style="color: #FF3824">拒绝</el-button>
            <i class="icon el-icon-phone"></i>
          </div>
          <div class="username" :class="[leftUser.online == '1' ? 'online' : 'offline']">
            <span style="font-size: 14px;">{{leftUser.name}}</span>
            <span style="font-size: 14px;margin-left: 10px">({{leftUser.online == '1'?'在线':'离线'}})</span>
          </div>
          <div class="more">
            <el-button type="text" size="small" v-if="!leftUser.customerId" @click="customerForm = {name:leftUser.name,email:leftUser.email,mobile:leftUser.mobile}">保存为联系人</el-button>
            <el-button type="text" size="small" v-if="leftUser.customerId && !ticketEditMode" class="pc-only" @click="createNewTicket">新建工单</el-button>
            <el-button type="text" style="color: red" size="small" @click="removeContact(leftUser)">{{disconnecting?'正在结束..':'结束'}}</el-button>
          </div>
        </div>
        <MsgBox ref="msgBox" class="msg-box" :left-user="leftUser" :right-user="currentUser"/>
        <div class="send-box" v-show="leftUser">
          <SendBox @send="sendChatMsg"/>
        </div>
        <div class="mask" v-if="!leftUser || leftUser.visitorId == ''">请选择一个对话</div>
        <div class="video-box" v-if="showCallPane">
          <video autoplay id="remote" class="large"></video>
          <div class="large" style="z-index: 7;display: flex;align-items: center;justify-content: center;color: #333333" v-if="!videoMeta.remote.ready">
            等待对方连接
          </div>
          <video autoplay id="local" class="thumb" muted></video>
          <div class="btn-group">
<!--            <div class="audio">-->
<!--              <i class="el-icon-phone-outline"></i>-->
<!--              <div v-if="!videoMeta.local.audio" class="line"></div>-->
<!--            </div>-->
            <div class="close" @click="hangup">
              <div class="center-block"></div>
            </div>
<!--            <div class="track">-->
<!--              <i class="el-icon-camera"></i>-->
<!--            </div>-->
          </div>
        </div>
      </div>
      <div class="customer pc-only" :style="{width: ticketEditMode?'450px':'250px'}" v-if="leftUser">
        <TicketEdit :show-back="true" @back="ticketEditMode = false" @submitSuccess="ticketEditMode = false" ref="ticketEdit" @cancel="ticketEditMode = false" v-if="ticketEditMode"></TicketEdit>
        <Customer :customer="leftUser" v-if="!ticketEditMode"></Customer>
      </div>
      <el-dialog :modal-append-to-body="false" title="添加联系人" @close="customerForm = null" :visible="customerForm!=null">
        <CustomerEdit @saveCustomer="saveCustomer" v-if="customerForm"  :customer-form="customerForm"></CustomerEdit>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {sendMessage} from "@/api/im";
import MsgBox from './components/message'
import Contact from './components/contact'
import SendBox from './components/send'
import Customer from "./components/customer";
import CustomerEdit from '@/view/customer/edit'
import TicketEdit from "@/view/ticket/components/ticket-edit-form"

import {encodeChatMessage,encodeContactMessage} from "@/modules/im/codec/encoder";
//监听消息
import {chatListeners,contactListeners} from "@/modules/im/command/listeners";
import {addListener,removeListener} from "@/modules/im/command/base";
import Constants from "@/modules/im/constants";
import {getHistoryMessages} from "@/api/im/history";
import {finishVisitor} from "@/api/im/contact";
import {checkEmail} from "@/libs/util";
import {saveCustomer} from "@/api/customer";
import {start, startCall, acceptCall, setListener, hangup} from "@/api/rtc/webrtc";

export default {
  name: "Chat",
  components:{
    Customer,
    MsgBox,
    Contact,
    SendBox,
    TicketEdit,
    CustomerEdit
  },
  data(){
    return {
      isExpand:false,
      leftUser: null,
      showContact:true,
      messages:{},
      disconnecting:false,
      customerForm: null,
      showCallPane:false,
      ticketEditMode:false,
      videoMeta:{
        local:{

        },
        remote:{
          ready: false
        }
      }
    }
  },
  created() {
    let that = this
    addListener(chatListeners,'Chat',this.handleChatMsg)
    addListener(contactListeners,'Chat',this.handleContactMsg)
    setListener({
      oniceconnectionstatechange: function (iceState) {
        switch (iceState) {
          case 'connected':
            that.$message.success('信道连接成功')
            that.videoMeta.remote.ready = true
            break
          case 'disconnected':
            that.$message.info('对方结束通话')
            that.showCallPane = false
            hangup()
            break
        }
      }
    })
  },
  mounted() {
    this.$nextTick(function () {
      if(window.innerWidth < 679) {
        this.showContact = false
      }
    })
  },
  methods:{
    createNewTicket() {
      let that = this
      this.ticketEditMode = true
      this.$nextTick(function () {
        that.$refs.ticketEdit.globalSelect('customer',{customerId:that.leftUser.customerId,name:that.leftUser.name,
          email:that.leftUser.email,mobile:that.leftUser.customerMobile})
      })
    },
    startCall() {
      this.showCallPane = true
      this.$nextTick(function (){
        start(document.getElementById('local'),document.getElementById('remote'))
        startCall(this.leftUser.visitorId)
      })
    },
    acceptCall() {
      this.showCallPane = true
      this.$nextTick(function (){
        start(document.getElementById('local'),document.getElementById('remote')).then(isSuccess => {
          if(isSuccess) {
            acceptCall(this.leftUser.visitorId, this.leftUser.callOffer)
            this.leftUser.callOffer = null
          }
        })
      })
    },
    hangup() {
      this.showCallPane = false
      hangup()
    },
    saveCustomer(form) {
      this.leftUser.customerId = form.customerId
      this.customerForm = null
    },
    toggleContact(){
      this.showContact = !this.showContact
    },
    handleChatMsg(obj){
      if(this.leftUser && (this.leftUser.visitorId == obj.sender || this.currentUser.userId == obj.sender)) {
        this.$refs.msgBox.handleNewMessage(obj)
        this.$refs.contactBox.handleChatMessage(obj)
      }else {
        if(this.messages.hasOwnProperty(obj.sender)){
          this.messages[obj.sender].push(obj)
        }
        this.$refs.contactBox.handleChatMessage(obj)
      }
    },
    handleContactMsg(obj){
      if(this.$refs.contactBox) {
        this.$refs.contactBox.handleContactMessage(obj)
      }
    },
    handleSelectContact(obj){
      if(obj == null || obj == '') {
        this.leftUser = null
        return
      }
      this.ticketEditMode = false
      if(!this.messages.hasOwnProperty(obj.visitorId)) {
        getHistoryMessages({contactId:obj.contactId,start:0}).then(res => {
          if(res.code == 200) {
            this.messages[obj.visitorId] = res.data
            this.$refs.contactBox.updateLatestMsg(obj.visitorId,res.data[res.data.length - 1])
            this.$refs.msgBox.resetMessages(this.messages[obj.visitorId])
          }
        })
      }else{
        this.$refs.msgBox.resetMessages(this.messages[obj.visitorId])
      }
      this.leftUser = obj
    },
    hideMsgBox(){
      this.leftUser = null
    },
    sendChatMsg(data) {
      let visitorId = this.leftUser.visitorId
      let msg = {sender:this.currentUser.userId,receiver:visitorId,date:new Date().getTime(),type:'1',msg:data}
      this.handleChatMsg(msg)
      sendMessage(encodeChatMessage(visitorId,this.leftUser.contactId,data))
    },
    handleSelectContactOffLine() {
      if(this.showCallPane) {
        this.showCallPane = false
        hangup()
        this.$message.info('对方断开连接')
      }
    },
    removeContact(visitor){
      let that = this
      if(this.disconnecting) {
        return
      }
      this.disconnecting = true
      finishVisitor(visitor.contactId).then(res => {
        if(res.code == 200) {
          this.hideMsgBox()
          delete this.messages[visitor.visitorId]
          this.$refs.contactBox.removeContact(visitor.visitorId)
        }
      }).finally(function (){
        that.disconnecting = false
      })
    }
  },computed:{
    currentUser(){
      return this.$store.state.userInfo
    }
  }
}
</script>

<style scoped lang="less">
  .expanded {
    background: #FAFAFA;
    transition: all .5s;
    transition-timing-function: ease-out;
    width: 100%;
    height: 100%;
    word-break: keep-all;
    opacity: 1;

    &.hidden{
      top: 100vh;
      bottom: 0;
      left: 100vw;
      right: 0;
      opacity: 0;
    }

    .header {
      display: flex;
      align-items: center;
      height: 40px;
      background: #409EFF;
      position: relative;
      color: #FFFFFF;
      .title {
        font-size: 16px;
        flex: 1;
        padding: 0 14px;
        line-height: 40px;
      }
      .close-btn {
        position: absolute;
        cursor: pointer;
        right: 0px;
        top: 0px;
        font-size: 20px;
        i {
          line-height: 40px;
          width: 40px;
          text-align: center;
        }
      }
    }

    .main {
      display: flex;
      width: 100%;
      position: absolute;
      top: 0px;
      bottom: 0;
      overflow: hidden;

      .contact {
        position: relative;
        z-index: 1;
        border-right: 1px solid #F0F0F0;

        .toggle-contact {
          position: absolute;
          top: 50%;
          right: -18px;
          font-size: 20px;
          line-height: 40px;
          text-align: center;
          transform: translateY(-20px);
          width: 20px;
          height: 40px;
          background: #FFFFFF;
        }
      }

      .message {
        flex: 1;
        display: flex;
        flex-direction: column;
        position: relative;
        .mask {
          position: absolute;
          top: 0;left: 0;right: 0;bottom: 0;
          background: #E4E4E4;
          color: #666666;
          display: flex;align-items: center;justify-content: center;
        }
        .toolbar {
          display: flex;
          align-items: center;
          padding: 5px 0;
          height: 30px;
          position: relative;

          .toggle{
            width: 100px;
            padding: 0 5px;
          }

          .call-handle {
            position: absolute;
            left: 10px;
            display: flex;
            border: 1px solid #E8E8E8;
            padding: 0 10px;
            margin: 0 10px;
            border-radius: 4px;

            .icon {
              position: absolute;
              left: -8px;
              color: #0091ff;
              top: -2px;
            }

            .accept {
              position: relative;
              &:after {
                content: '';
                position: absolute;
                height: 100%;
                width: 1px;
                background: #E8E8E8;
                right: -6px;
                top: 0;
              }
            }
          }
          .username {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            vertical-align: bottom;
            transition: color .5s;
            &.offline {
              color: #888888;
            }
          }
          .more{
            text-align: right;
            padding: 0 20px;
            position: absolute;
            right: 0;
            display: flex;
            align-items: center;
          }
        }
        .msg-box {
          width: 100%;
          top:40px;
          bottom: 160px;
          position: absolute;
        }
        .send-box {
          position: absolute;
          height: 160px;
          bottom: 0;
          width: 100%;
        }

        .video-box {
          position: absolute;
          bottom: 0;
          top: 0;
          width: 100%;
          z-index: 3;
          background: #FFFFFF;

          .large {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 4;
            width: 100%;
            height: 100%;
            object-fit: cover;

          }
          .thumb {
            position: absolute;
            top: 0;
            right: 0;
            width: 200px;
            height: 150px;
            z-index: 5;
            object-fit: cover;
          }
          .btn-group {
            position: absolute;
            bottom: 50px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 8;
            .audio {
              border-radius: 50%;
              border: 1px solid #FFF;
              background: #FFF;
              color: #333333;
              width: 40px;
              height: 40px;
              text-align: center;
              line-height: 40px;
              margin-right: 20px;
              cursor: pointer;
              box-shadow: 0px 0px 10px #8E8E8E;
              .line {
                width: 40px;
                height: 2px;
                background: #333333;
                transform: rotate(45px);
              }
            }
            .close {
              border-radius: 50%;
              width: 60px;
              height: 60px;
              display: flex;
              align-items: center;
              justify-content: center;
              cursor: pointer;
              background: #FF3824;
              .center-block {
                background: #FFF;
                width: 15px;
                height: 15px;
              }
            }
            .track {
              border-radius: 50%;
              border: 1px solid #FFF;
              box-shadow: 0px 0px 10px #8E8E8E;
              background: #FFF;
              color: #333333;
              width: 40px;
              height: 40px;
              text-align: center;
              line-height: 40px;
              margin-left: 20px;
              cursor: pointer;
            }
          }
        }
      }

      .customer {
        width: 250px;
        background: #FFF;
        border-left: 1px solid #F0F0F0;
        overflow-y: auto;
        transition: width .3s;
      }
    }
  }
  @media(max-width: 679px) {
    .expanded {
      .main {
        .contact {
          position: absolute;
          z-index: 1;
          left: 0;
          right: 0;
          top: 0px;
          bottom: 0;
          display: flex;

          &.hidden{
            right: unset;
          }
          .mask {
            flex: 1;
            background: rgba(0,0,0,.2);
          }
        }
        .message {
          .msg-box {
            width: 100%;
            top: 40px;
            bottom: 50px;
          }
          .send-box {
            position: fixed;
            height: 50px;
          }

          .video-box {
            position: absolute;
            bottom: 0;
            top: 0;
            width: 100%;
            z-index: 3;
            background: #FFFFFF;

            .large {
              width: 100%;
              height: 100%;
              object-fit:cover;
            }
            .thumb {
              position: absolute;
              z-index: 4;
              object-fit:cover;
              right: 0;
              top: 0;
              width: 150px;
              height: 200px;
            }
          }
        }
      }
    }
  }
</style>
